package cn.yunyichina.provider.guide.service.impl;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.common.utils.CollectionUtils;

import cn.yunyichina.provider.framework.dubbo.service.HisifaceService;
import cn.yunyichina.provider.guide.GuideConstants;
import cn.yunyichina.provider.guide.dao.InstanceDao;
import cn.yunyichina.provider.guide.dao.InstanceNodeDao;
import cn.yunyichina.provider.guide.dao.InstanceRelationDao;
import cn.yunyichina.provider.guide.dao.RegisterStatusDao;
import cn.yunyichina.provider.guide.dao.TemplateDao;
import cn.yunyichina.provider.guide.entity.Instance;
import cn.yunyichina.provider.guide.entity.RegisterStatus;
import cn.yunyichina.provider.iface.entity.ErrorCodeDefine;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.hisiface.leads.RegisterGuideInfoVo;
import cn.yunyichina.provider.iface.entity.hisiface.leads.RegisterGuideInfoVoResponse;
import cn.yunyichina.utils.convert.JsonUtils;

/**
 * 导医,定时更新挂号状态
 * @author adriftor
 *
 */
@Service("guidesyncServiceImpl")
public class GuideSyncServiceImpl  {
	
	private static final Logger logger = LoggerFactory.getLogger(GuideSyncServiceImpl.class);
	
	
	
	@Resource
	private InstanceDao instanceDao;
	
	@Resource
	private TemplateDao templateDao;
	
	@Resource
	private InstanceNodeDao instanceNodeDao;
	
	@Resource
	private InstanceRelationDao instanceRelationDao;
	
	@Resource
	private GuideTemplateServiceImpl guideTemplateService;
	
	@Resource
	private GuideInstanceServiceImpl guideInstanceService;
	
	
	private static Boolean isRunning = false;
	
	@Resource
	private GuideSyncStopServiceImpl guideSyncEndService;

	
	@Resource
	private RegisterStatusDao registerStatusDao;
	
	/**
	 * 定时同步导医状态记录
	 * @param strJson
	 * @param instanceId
	 */
	public void doGuideSync() {
		
		if (isRunning) {
			logger.info("定时同步导医状态记录正在运行,禁止重入");
			return;
		}
		
		isRunning = true;
		
		try {
			
			logger.info("sync:start");
			Instance instance = new Instance();
			Calendar c = Calendar.getInstance();
			c.add(Calendar.DATE, -1);
			instance.setBeginCreatedTime(GuideConstants.YYYYMMDDHHMMSS.format(c.getTime()));
			instance.setRunStatus(GuideConstants.INSTANCE_RUN_STATUS_RUNNING);		
			List<Map<String,Object>> listSchCount = instanceDao.selectSchCount(GuideConstants.YYYYMMDDHHMMSS.format(c.getTime()));
			
			logger.info("size="+listSchCount);
			
			if (CollectionUtils.isNotEmpty(listSchCount)) {
				logger.info("size="+listSchCount.size());
				for (Map<String,Object> map : listSchCount) {
					
					logger.info("map="+JsonUtils.toJsonString(map));
					
					String orgCode = (String) map.get("org_code");
//					Long count = (Long) map.get("cnt");
					List<Instance> listInstance = instanceDao.selectSch(GuideConstants.YYYYMMDDHHMMSS.format(c.getTime()), orgCode);
					
					logger.info("listInstance-size="+listInstance.size());
					
					//调用HIS接口
					RegisterGuideInfoVo registerGuideInfoVo = new RegisterGuideInfoVo();
					
					c = Calendar.getInstance();
					c.add(Calendar.DATE, -1);
					registerGuideInfoVo.setBeginDate(GuideConstants.YYYYMMDD.format(c.getTime()));
					c = Calendar.getInstance();
					c.add(Calendar.DATE, 1);
					registerGuideInfoVo.setEndDate(GuideConstants.YYYYMMDD.format(c.getTime()));
					registerGuideInfoVo.setHospitalCode(orgCode);
					
					for (Instance thisInstance : listInstance) {
						registerGuideInfoVo.setPatCardNo(thisInstance.getPatCardNo());
						registerGuideInfoVo.setYytOrdNum(thisInstance.getOrderNo());
						registerGuideInfoVo.setPatCardType(thisInstance.getPatCardType());
						registerGuideInfoVo.setAppCode(thisInstance.getPlatformCode());
						
						RegisterGuideInfoVoResponse registerGuideInfoVoResponse = guideInstanceService.getHisRegisterStatus(thisInstance);
						
						try {
							if (registerGuideInfoVoResponse != null) {
								RegisterStatus registerStatus = new RegisterStatus();
								registerStatus.setOrgCode(thisInstance.getOrgCode());
								registerStatus.setHisRegisterStatusCode(registerGuideInfoVoResponse.getStatus());
								List<RegisterStatus> listRegisterStatus = registerStatusDao.select(registerStatus);
								
								if (CollectionUtils.isEmpty(listRegisterStatus)) {
									logger.error("没有找到对应的挂号状态对应关系:"+JsonUtils.toJsonString(registerStatus));
								}
								else {
									registerStatus = listRegisterStatus.get(0);
									
									if ( ! thisInstance.getRegisterStatus().equals(registerStatus.getPlatformRegisterStatusCode())) {
						
										logger.info("状态更新："+thisInstance.getRegisterStatus()+"--->>"+registerStatus.getPlatformRegisterStatusCode()+",order_no="+thisInstance.getOrderNo());
										thisInstance.setRegisterStatus(registerStatus.getPlatformRegisterStatusCode());
										thisInstance.setRegisterStatusName(registerStatus.getPlatformRegisterStatusName());
										instanceDao.update(thisInstance);
										
										//就诊结束
										if (GuideConstants.REGISTER_STATUS_NED_VISIT.equals(thisInstance.getRegisterStatus())) {
											
											guideInstanceService.stopGuideInstance(JsonUtils.toJsonString(thisInstance));
										}
										else {
											guideInstanceService.runGuideInstance(thisInstance.getId());
										}
									}
								}
								
							}
							else {
								logger.error("获取状态数据异常，无法更新状态");
							}
						} catch (Exception e) {
							logger.error("根据新的挂号状态，流程处理异常："+JsonUtils.toJsonString(thisInstance),e);
						}
						
					}//for
					
//					HisifaceService.getHisifaceClient().listGuideHisRegisterStatus(guideRegisterStatusVo);
				}
			}

			logger.info("sync--ok");
		}
		catch (Exception ex) {
			logger.error(ErrorCodeDefine.GUIDE_COMMON,"定时更新挂号状态异常",ex);
		}
		finally {
			isRunning = false;
		}
		
		//运行定时结束过期的导医流程任务
		try {
			guideSyncEndService.schEndInstance();
		} catch (Exception e) {
		}
	}
	
	private void callHis(Instance instance,RegisterGuideInfoVo registerGuideInfoVo) {
		RegisterGuideInfoVoResponse registerGuideInfoVoResponse = null;
		boolean bStatus = true;
		try {
			logger.info("registerGuideInfoVo="+JsonUtils.toJsonString(registerGuideInfoVo));
			ResCommon<RegisterGuideInfoVoResponse> res = HisifaceService.getHisifaceClient().getRegisterGuideInfo(registerGuideInfoVo);
			logger.info("res="+JsonUtils.toJsonString(res));
			if (res.getResultMessage().indexOf("无记录") >= 0 ) {
				logger.info("HIS没有对应的挂号记录："+JsonUtils.toJsonString(registerGuideInfoVo));
			}
			registerGuideInfoVoResponse = res.getResult();			
			if (registerGuideInfoVoResponse == null) {
				bStatus = false;
				logger.info("从HIS获取挂号状态异常，返回结果为null,"+JsonUtils.toJsonString(instance));
			}
			
		} catch (Exception e) {
			bStatus = false;
			logger.error("获取挂号状态信息异常"+JsonUtils.toJsonString(instance),e);
		}
		
		
		try {
			if (bStatus) {
				RegisterStatus registerStatus = new RegisterStatus();
				registerStatus.setOrgCode(instance.getOrgCode());
				List<RegisterStatus> listRegisterStatus = registerStatusDao.select(registerStatus);
				registerStatus.setHisRegisterStatusCode(registerGuideInfoVoResponse.getStatus());
				if (CollectionUtils.isEmpty(listRegisterStatus)) {
					logger.error("没有找到对应的挂号状态对应关系:"+JsonUtils.toJsonString(registerStatus));
					return;
				}
				registerStatus = listRegisterStatus.get(0);
				
				if ( ! instance.getRegisterStatus().equals(registerStatus.getPlatformRegisterStatusCode())) {
	
					logger.info("状态更新："+instance.getRegisterStatus()+"--->>"+registerStatus.getPlatformRegisterStatusCode()+",order_no="+instance.getOrderNo());
					instance.setRegisterStatus(registerStatus.getPlatformRegisterStatusCode());
					instance.setRegisterStatusName(registerStatus.getPlatformRegisterStatusName());
					instanceDao.update(instance);
					
					//就诊结束
					if (GuideConstants.REGISTER_STATUS_NED_VISIT.equals(instance.getRegisterStatus())) {
						
						guideInstanceService.stopGuideInstance(JsonUtils.toJsonString(instance));
					}
					else {
						guideInstanceService.runGuideInstance(instance.getId());
					}
				}
			}
		} catch (Exception e) {
			logger.error("根据新的挂号状态，流程处理异常："+JsonUtils.toJsonString(instance),e);
		}
	}

}
